<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1>{{ isLoginMode ? '登录' : '注册' }}</h1>
        <p>{{ isLoginMode ? '欢迎回来！' : '创建您的账户' }}</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="0"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item v-if="!isLoginMode" prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="昵称"
            prefix-icon="Avatar"
            clearable
          />
        </el-form-item>

        <el-form-item v-if="!isLoginMode" prop="email">
          <el-input
            v-model="form.email"
            placeholder="邮箱（可选）"
            prefix-icon="Message"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item v-if="!isLoginMode" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="确认密码"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleSubmit"
            style="width: 100%"
          >
            {{ isLoginMode ? '登录' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <span>{{ isLoginMode ? '还没有账户？' : '已有账户？' }}</span>
        <el-button type="text" @click="toggleMode">
          {{ isLoginMode ? '立即注册' : '立即登录' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { LoginRequest, RegisterRequest } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const formRef = ref<FormInstance>()
const isLoginMode = ref(true)
const loading = ref(false)

const form = reactive({
  username: '',
  nickname: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = computed<FormRules>(() => ({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  nickname: isLoginMode.value ? [] : [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '昵称长度为1-50个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: isLoginMode.value ? [] : [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}))

// 切换登录/注册模式
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  // 清空表单
  Object.keys(form).forEach(key => {
    ;(form as any)[key] = ''
  })
  formRef.value?.clearValidate()
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isLoginMode.value) {
      // 登录
      const loginData: LoginRequest = {
        username: form.username,
        password: form.password
      }
      
      const result = await userStore.login(loginData)
      if (result.success) {
        ElMessage.success('登录成功！')
        router.push('/')
      } else {
        ElMessage.error(result.message || '登录失败')
      }
    } else {
      // 注册
      const registerData: RegisterRequest = {
        username: form.username,
        password: form.password,
        nickname: form.nickname,
        email: form.email || undefined
      }
      
      const result = await userStore.register(registerData)
      if (result.success) {
        ElMessage.success('注册成功！')
        router.push('/')
      } else {
        ElMessage.error(result.message || '注册失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 8px 40px rgba(0, 0, 0, 0.08);
  padding: 48px;
  width: 100%;
  max-width: 420px;
  border: 1px solid #f1f3f4;
}

.login-header {
  text-align: center;
  margin-bottom: 32px;
}

.login-header h1 {
  font-size: 2.2rem;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-header p {
  color: #6c757d;
  margin: 0;
  font-size: 1rem;
  font-weight: 400;
}

.el-form-item {
  margin-bottom: 20px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
}

.login-footer span {
  margin-right: 8px;
}

@media (max-width: 480px) {
  .login-card {
    padding: 24px;
    margin: 0 16px;
  }
}
</style>
